## Kucik, Peritz, Puig (2022) "Legalization and Compliance"
## Replication of Precedent Descriptive Statistics
## MAIN RESULTS -- TABLE 3

rm(list=ls(all=T))
library(haven)

# Set your working directory here
setwd("/Users/lperitz/Dropbox/JK_LP/RulingExpansion/BJPS/bjps22_replication")

## Data -----------------------------------------
d <- read_dta("comply_data.dta")

## Subset of cases with adverse rulings
d.sub <- subset(d, select = c("ds", "complainant", "respondent", "comply_ontime", "time_to_comply", "follow", "extend", "distinguish", "narrow"))
d.sub1 <- d.sub[!is.na(d$comply_ontime),] 
nrow(d.sub1)

## Table 3: total adverse rulings by respondent
T3.1 <- table(d.sub1$respondent)
T3.1

## Table 3: on time compliance by respondent
T3.2 <- table(d.sub1$respondent,d.sub1$comply_ontime)
T3.2
table(d.sub1$comply_ontime)

## Table 3: compliance rate by respondent
T3.3<- aggregate(x=d.sub1$comply_ontime, by=list(d.sub1$respondent), FUN=mean)
T3.3
mean(d.sub1$comply_ontime)

## Table 3: Average days to compliance
d.sub2 <- na.omit(subset(d.sub1, select=c("respondent", "time_to_comply")))
T3.4 <- aggregate(x=d.sub2$time_to_comply, by=list(d.sub2$respondent), FUN=mean)
T3.4
mean(d.sub2$time_to_comply)

## Table 3: Extension rate
d.sub$all_prec <- apply(d.sub[,6:9], 1, sum)
d.sub3 <- na.omit(d.sub[,c(3,7,10)])
r <- unique(d.sub3$respondent)

ex_rate <- matrix(NA, nrow=length(r), ncol = 3)
rownames(ex_rate) <- r
colnames(ex_rate) <- c("extensions", "all_precedent", "ex_rate")
for(i in 1:length(r)){
  ex_rate[i,1:2]<-apply(d.sub3[d.sub3$respondent==r[i],2:3], MARGIN=2, sum)
  }
ex_rate[,3]<-(round(ex_rate[,1]/ex_rate[,2], digits=3))*100

ex_rate

## END 
